package com.jn.zhinongbao.adapter;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.supportingagriculturaltreasures.adapter.ProductAdapter;
import com.example.supportingagriculturaltreasures.bean.Product;
import com.example.supportingagriculturaltreasures.database.DatabaseHelper;
import com.google.android.material.tabs.TabLayout;

import java.util.ArrayList;
import java.util.List;

public class SearchActivity extends AppCompatActivity {

    private EditText etSearch;
    private Button btnSearch;
    private ImageButton btnBack;
    private TabLayout searchTabs;
    private RecyclerView recyclerSearchResults;
    private ProductAdapter adapter;
    private DatabaseHelper databaseHelper;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search);
        
        databaseHelper = new DatabaseHelper(this);
        
        initViews();
        setupSearchTabs();
        setupRecyclerView();
        setupClickListeners();
        
        // 设置焦点到搜索框
        etSearch.requestFocus();
    }

    private void initViews() {
        etSearch = findViewById(R.id.et_search);
        btnSearch = findViewById(R.id.btn_search);
        btnBack = findViewById(R.id.btn_back);
        searchTabs = findViewById(R.id.search_tabs);
        recyclerSearchResults = findViewById(R.id.recycler_search_results);
    }

    private void setupSearchTabs() {
        searchTabs.addTab(searchTabs.newTab().setText("售卖信息"));
        searchTabs.addTab(searchTabs.newTab().setText("采购信息"));
        searchTabs.addTab(searchTabs.newTab().setText("店铺"));

        searchTabs.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                // 根据选中的tab进行搜索
                performSearch();
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {}

            @Override
            public void onTabReselected(TabLayout.Tab tab) {}
        });
    }

    private void setupRecyclerView() {
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        recyclerSearchResults.setLayoutManager(layoutManager);
        
        List<Product> products = new ArrayList<>();
        adapter = new ProductAdapter(products);
        recyclerSearchResults.setAdapter(adapter);
    }

    private void setupClickListeners() {
        btnBack.setOnClickListener(v -> {
            finish(); // 关闭当前Activity，返回上一个Activity
        });

        btnSearch.setOnClickListener(v -> performSearch());

        etSearch.setOnEditorActionListener((v, actionId, event) -> {
            if (actionId == EditorInfo.IME_ACTION_SEARCH || 
                (event != null && event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) {
                performSearch();
                return true;
            }
            return false;
        });
    }

    private void performSearch() {
        String query = etSearch.getText().toString().trim();
        if (TextUtils.isEmpty(query)) {
            Toast.makeText(this, "请输入搜索关键词", Toast.LENGTH_SHORT).show();
            return;
        }

        // 获取当前选中的Tab
        int selectedTab = searchTabs.getSelectedTabPosition();
        String category = getSelectedCategory(selectedTab);
        
        // 从数据库搜索
        List<Product> searchResults = searchProducts(query, category);
        adapter.updateProducts(searchResults);
        
        Toast.makeText(this, "找到 " + searchResults.size() + " 条结果", Toast.LENGTH_SHORT).show();
    }

    private String getSelectedCategory(int tabPosition) {
        switch (tabPosition) {
            case 0:
                return null; // 售卖信息，搜索所有商品
            case 1:
                return "采购"; // 采购信息
            case 2:
                return "店铺"; // 店铺
            default:
                return null;
        }
    }

    private List<Product> searchProducts(String keyword, String category) {
        // 使用DatabaseHelper搜索
        return databaseHelper.searchProducts(keyword, category);
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        finish();
    }
} 